//
//  JSChangeInfoVC.m
//  NiubilityProject
//
//  Created by Apple on 2017/11/29.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "JSChangeInfoVC.h"
#import "EditAvatarCell.h"
#import "EditDataPhotoCell.h"
#import "EditDataTitleCell.h"
#import "UICollectionReusablePlaceholderView.h"
#import "JSPictureManager.h"
#import <TZImageManager.h>
#import "PhotoModel.h"
#import "JSCountryInfoModel.h"
#import "JSSettingMoodVC.h"
#import "CuiPickerView.h"
#import "JSCountrySelectView.h"
#import "JSSelectGenderView.h"
#import "JSCityListViewController.h"
@interface JSChangeInfoVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,TZImagePickerControllerDelegate,QMUITextFieldDelegate,CuiPickViewDelegate,JSCountrySelectViewDelegate,JSGenderSelectViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) NSArray *contens;
@property (nonatomic, strong) NSMutableArray *photos;
@property (nonatomic, strong) UserInfo *editInfo;
@property (nonatomic, assign) BOOL isOnly;
@property (nonatomic, strong) UIImage *useriConImage;
@property (nonatomic, strong) NSString *nameStr;
@property (nonatomic, strong) NSString *moodStr;
@property (nonatomic, strong) NSString *timeStr;
@property (nonatomic, strong) NSString *genderStr;
@property (nonatomic, assign) UserGender sex;
@property (nonatomic, strong) NSString *countryStr;
@property (nonatomic, strong) NSString *cityStr;
@property(nonatomic, weak) QMUIDialogTextFieldViewController *currentTextFieldDialogViewController;
@property (nonatomic, strong) CuiPickerView *cuiPickerView;
@property (nonatomic, strong) JSSelectGenderView *genderSelectView;
@property (nonatomic, strong) JSCountrySelectView *countrySelectView;
@property (nonatomic, strong) JSCountryInfoModel *selectCityModel;
/** 性别 */
@property (nonatomic, assign) UserGender gender;
@property (nonatomic, strong) NSMutableDictionary *parmas;
@end

@implementation JSChangeInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    _titles = @[@"knickname",@"MySignature",@"birthdayLoca",@"genderLoca",@"countryLoca",@"cityLoca"];
    self.nameStr = userManager.curUserInfo.username;
    self.moodStr = userManager.curUserInfo.mood;
    self.timeStr = userManager.curUserInfo.birthday;
    self.gender  = userManager.curUserInfo.sex;
    self.genderStr = userManager.curUserInfo.sex == UserGenderMale ? JSLocalizedString(@"genderMan"):JSLocalizedString(@"genderWoman");
    self.countryStr = JSLocalizeIsChina()?userManager.curUserInfo.city.country_zh:userManager.curUserInfo.city.country;
    self.cityStr = JSLocalizeIsChina()?userManager.curUserInfo.city.state_zh:userManager.curUserInfo.city.state;
    _contens = @[
                 self.nameStr,
                 self.moodStr,
                 self.timeStr,
                  self.genderStr,
                 self.countryStr,
                 self.cityStr,
                 ];
    self.photos = userManager.curUserInfo.photo.mutableCopy;
    JS_WeakSelf(self)
    [RACObserve(self, editInfo) subscribeNext:^(id x) {
        UserInfo *u = (UserInfo *)x;
        JSLog(@"%@", u);
    }];
    [RACObserve(self, nameStr) subscribeNext:^(id x) {
        [weakself resetConten];
        [weakself.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:2]]];
    }];
    [RACObserve(self, moodStr) subscribeNext:^(id x) {
        [weakself resetConten];
        [weakself.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:2]]];
    }];
    [RACObserve(self, timeStr) subscribeNext:^(id x) {
        [weakself resetConten];
        [weakself.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:2]]];
    }];
    [RACObserve(self, genderStr) subscribeNext:^(id x) {
        [weakself resetConten];
        [weakself.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:3 inSection:2]]];
    }];
    [RACObserve(self, countryStr) subscribeNext:^(id x) {
        [weakself resetConten];
        [weakself.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:4 inSection:2]]];
    }];
    [RACObserve(self, cityStr) subscribeNext:^(id x) {
        [weakself resetConten];
        [weakself.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:5 inSection:2]]];
    }];
    self.editInfo = userManager.curUserInfo;
}
- (void)resetConten{
    self.contens = @[self.nameStr,
                         self.moodStr,
                         self.timeStr,
                         self.genderStr,
                         self.countryStr,
                         self.cityStr,];
}
- (void)setNavigationItemsIsInEditMode:(BOOL)isInEditMode animated:(BOOL)animated{
    [super setNavigationItemsIsInEditMode:isInEditMode animated:animated];
    self.title = JSLocalizedString(@"modifyData");
    self.navigationItem.rightBarButtonItem = [QMUINavigationButton barButtonItemWithType:QMUINavigationButtonTypeNormal title:JSLocalizedString(kLocalizableOk) position:QMUINavigationButtonPositionRight target:self action:@selector(save:)];
}
- (void)didInitialized{
    [super didInitialized];
    self.view.backgroundColor = [UIColor whiteColor];
    _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:[[UICollectionViewFlowLayout alloc] init]];
    [self.view addSubview:_collectionView];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.dataSource = self;
    _collectionView.delegate   = self;
    [_collectionView registerNib:[UINib nibWithNibName:@"EditAvatarCell" bundle:nil] forCellWithReuseIdentifier:@"EditAvatarCellID"];
    [_collectionView registerNib:[UINib nibWithNibName:@"EditDataPhotoCell" bundle:nil] forCellWithReuseIdentifier:@"EditDataPhotoCellID"];
    [_collectionView registerNib:[UINib nibWithNibName:@"EditDataTitleCell" bundle:nil] forCellWithReuseIdentifier:@"EditDataTitleCellID"];
    [_collectionView registerClass:[UICollectionReusablePlaceholderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionReusablePlaceholderViewID"];
    // 日期选择
    _cuiPickerView = [[CuiPickerView alloc]init];
    _cuiPickerView.frame = CGRectMake(0, SCREEN_HEIGHT, self.view.frame.size.width, 200);
    _cuiPickerView.delegate = self;
    _cuiPickerView.curDate=[NSDate date];
    
    _genderSelectView = [[JSSelectGenderView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 168)];
    _genderSelectView.delegate = self;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    if (section == 1) {
        return self.photos.count<9?self.photos.count+1:self.photos.count;
    }
    return 6;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        EditAvatarCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EditAvatarCellID" forIndexPath:indexPath];
        JS_WeakSelf(cell);
        JS_WeakSelf(self)
        if (self.useriConImage) {
            cell.userIconImageView.image = [[self.useriConImage imageByResizeToSize:CGSizeMake(100, 100)] imageByRoundCornerRadius:50];
        }else{
            [cell.userIconImageView setImageWithURL:[NSURL URLWithString:self.editInfo.avatar] placeholder:defauldUserIcon options:YYWebImageOptionIgnoreDiskCache completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
                weakself.useriConImage = image;
                weakcell.userIconImageView.image = [[image imageByResizeToSize:CGSizeMake(100, 100)] imageByRoundCornerRadius:50];
            }];
        }
        return cell;
    }else if (indexPath.section == 1){ //
        EditDataPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EditDataPhotoCellID" forIndexPath:indexPath];
        if (indexPath.row < self.photos.count) {
            PhotoModel *m = self.photos[indexPath.row];
            cell.photoModel = m;
            cell.indexPath  = indexPath;
            JS_WeakSelf(self)
            [cell setRemoveImage:^(NSIndexPath *indx) {
                [weakself.photos removeObjectAtIndex:indx.row];
                [weakself.collectionView reloadData];
            }];
        }else{
            cell.isHaveImage = NO;
        }
        return cell;
    }else{ //
        EditDataTitleCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"EditDataTitleCellID" forIndexPath:indexPath];
        cell.titleL.text = JSLocalizedString(self.titles[indexPath.row]);
        cell.contenL.text= self.contens[indexPath.row];
        return cell;
    }
    return nil;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 3;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0.001;
}
- (CGSize) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section == 2) {
        return CGSizeMake(SCREEN_WIDTH, kRealValue(10));
    }
    return CGSizeZero;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        UICollectionReusablePlaceholderView *placehold = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"UICollectionReusablePlaceholderViewID" forIndexPath:indexPath];
        placehold.backgroundColor = JS_colorWithHex(0xf7f7f7);
        return placehold;
    }
    return nil;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return CGSizeMake(SCREEN_WIDTH, kRealValue(80));
    }else if (indexPath.section == 1){
        CGFloat w = flat(SCREEN_WIDTH / 3) - 1;
        return CGSizeMake(w, w);
    }else{
        return CGSizeMake(SCREEN_WIDTH, kRealValue(44));
    }
    return CGSizeZero;
}
- (UIImage *)navigationBarShadowImage{
    return [UIImage qmui_imageWithColor:JS_colorWithHex(0xe7e7e7) size:CGSizeMake(1, flat(0.5)) cornerRadius:0];
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    JS_WeakSelf(self)
    if (indexPath.section == 0) { // 头像选择
        self.isOnly = YES;
        [JSPictureManager showUseriConPickerViewControllerTarget:self cropRect:CGRectZero isUseDefauld:YES];
    }else if (indexPath.section == 1){ // 图片选择
        if (indexPath.row < self.photos.count) {
            return;
        }
        self.isOnly = NO;
        [JSPictureManager showDefauldPickerViewControllerTarget:self maxCount:9 - self.photos.count];
        
    }else{
        switch (indexPath.row) {
            case 0:{ //昵称
                QMUIDialogTextFieldViewController *dialogViewController = [[QMUIDialogTextFieldViewController alloc] init];
                self.currentTextFieldDialogViewController = dialogViewController;
                dialogViewController.title = JSLocalizedString(@"registername");
                dialogViewController.textField.delegate = self;
                dialogViewController.textField.placeholder = JSLocalizedString(@"knickname");
                [dialogViewController addCancelButtonWithText:JSLocalizedString(kLocalizableCancel) block:nil];
                [dialogViewController addSubmitButtonWithText:JSLocalizedString(kLocalizableOk) block:^(QMUIDialogViewController *aDialogViewController) {
                    [aDialogViewController hide];
                    QMUIDialogTextFieldViewController *dialog = (QMUIDialogTextFieldViewController *)aDialogViewController;
                    weakself.nameStr = dialog.textField.text;
                }];
                [dialogViewController show];
                break;
            }
            case 1:{ // 签名
                JSSettingMoodVC *vc = [[JSSettingMoodVC alloc] init];
                vc.mood = self.moodStr;
                vc.EnterMood = ^(NSString *moodStr){
                    weakself.moodStr = moodStr;
                };
                [self.navigationController presentViewController:vc animated:YES completion:nil];
                break;
            }
            case 2:{ // 日期选择
                [self.cuiPickerView showMaskView];
                break;
            }
            case 3:{ // 性别
                [self.genderSelectView showMaskView];
                break;
            }
            case 4:{ // 国家选择
                [self.countrySelectView showMaskView];
                break;
            }
            case 5:{ // 城市选择
                if (!self.countryStr.length) {
                    [JSAlertHelper showFailHideAfterDelay:2 text:JSLocalizedString(@"alterCountryLoca") inView:self.view animation:YES];
                    return;
                }
                JS_WeakSelf(self)
                JSCityListViewController *vc = [[JSCityListViewController alloc] init];
                vc.title = self.countryStr;
                vc.params[@"country"] = vc.title;
                vc.shouldShowSearchBar = YES;
                [vc setDidSelectCity:^(JSCountryInfoModel *cityM) {
                    weakself.selectCityModel = cityM;
                    if (JSLocalizeIsChina()) {
                        weakself.cityStr = cityM.state_zh;
                    }else{
                        weakself.cityStr = cityM.state;
                    }
                }];
                [self.navigationController pushViewController:vc animated:YES];
                break;
            }
        }
    }
}
#pragma mark ---------------- 图片选择 ----------------
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    if (self.isOnly) {
        self.useriConImage = photos.firstObject;
        [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]]];
    }else{
        if (!isSelectOriginalPhoto) {
            JS_WeakSelf(self)
           __block int i = 0;
            for (id asset in assets) {
                [[TZImageManager manager] getOriginalPhotoWithAsset:asset completion:^(UIImage *photo, NSDictionary *info) {
                    JSLog(@"%@", NSStringFromCGSize(photo.size));
                    PhotoModel *m = [[PhotoModel alloc] init];
                    m.image = photo;
                    [weakself.photos addObject:m];
                    i++;
                    if (i == assets.count) {
                        [weakself.collectionView reloadData];
                    }
                }];
            }
        }else{
            [self.photos addObjectsFromArray:photos];
        }
    }
    
    
}
#pragma mark --------提交个人信息--------
-(void)save:(UIButton *)sender {
    // 1.判断基本信息是否完善
    if (!self.nameStr.length
        ||!self.moodStr.length
        ||!self.timeStr.length
        ||!self.gender
        ||!self.countryStr.length
        ||!self.cityStr.length
        ||!self.useriConImage
        ||!self.photos.count) {
        return;
    }
    self.parmas = @{}.mutableCopy;
    // 上传头像
    RACSignal *avatarSignal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        [UserManager uploadImage:@[self.useriConImage] progress:^(CGFloat progress) {
            
        } respons:^(id respons) {
            JSLog(@"avatarSignal %@", respons);
            [subscriber sendNext:@"1"];
            [subscriber sendCompleted];
        } failur:^(NSError *error) {
            [subscriber sendError:error];
        }];
        return [RACDisposable disposableWithBlock:^{
            
        }];
    }];
    // 上传相册
    NSMutableArray *p = @[].mutableCopy;
    NSMutableArray *oldPaths = @[].mutableCopy;
    for (PhotoModel *photoM in self.photos) {
        if (photoM.image) {
            [p addObject:photoM.image];
        }else{
            [oldPaths addObject:photoM.src];
        }
    }
    RACSignal *photoSignal = nil;
    if (p.count) {
        photoSignal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            [UserManager uploadImage:p.copy progress:^(CGFloat progress) {
                
            } respons:^(id respons) {
                JSLog(@"photoSignal %@", respons);
                JSLog(@"oldPaths %@", [oldPaths componentsJoinedByString:@","]);
                [subscriber sendNext:@"2"];
                [subscriber sendCompleted];
            } failur:^(NSError *error) {
                [subscriber sendError:error];
            }];
            return [RACDisposable disposableWithBlock:^{
                
            }];
        }];
    }else{
        photoSignal = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            [subscriber sendNext:[oldPaths componentsJoinedByString:@","]];
            [subscriber sendCompleted];
            return [RACDisposable disposableWithBlock:^{
                
            }];
        }];
    }
    [[[avatarSignal throttle:1]concat:photoSignal] subscribeNext:^(id x) {
        JSLog(@"fuck -> %@",x);
    }];
}
-(RACSignal *)uploadImageSifnal:(NSArray *)images{
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [UserManager uploadImage:images progress:^(CGFloat p) {
            
        } respons:^(id r) {
            NSMutableArray *paths = @[].mutableCopy;
            NSDictionary *dic = (NSDictionary *)r;
            if ([dic[@"status"] integerValue] == 1) {
                if (ValidDict(dic[@"data"])) {
                    for (NSDictionary *key in [dic[@"data"] allKeys]) {
                        [paths addObject:dic[@"data"][key] ];
                    }
                }else if (ValidArray(dic[@"data"])){
                    [paths addObjectsFromArray:dic[@"data"]];
                }
              [subscriber sendNext:[paths componentsJoinedByString:@","]];
              [subscriber sendCompleted];
            }else{
                // 构建error
                NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:4 userInfo:nil];
                if (error) {
                    [subscriber sendError:error];
                }
            }
        } failur:^(NSError *e) {
            [subscriber sendError:e];
        }];
        return [RACDisposable disposableWithBlock:^{
            
        }];
    }];
}
- (BOOL)textFieldShouldReturn:(QMUITextField *)textField {
    if (self.currentTextFieldDialogViewController.submitButton.enabled) {
        self.nameStr = self.currentTextFieldDialogViewController.textField.text;
        [self.currentTextFieldDialogViewController hide];
    } else {
        [QMUITips showSucceed:@"请输入文字" inView:self.currentTextFieldDialogViewController.modalPresentedViewController.view hideAfterDelay:2.0];
    }
    return NO;
}
#pragma mark - CuiPickViewDelegate 时间选择回调
-(void)didFinishPickView:(NSString*)date dateStr:(NSString *)dateStr{
    JSLog(@"%@--%@--%@", dateStr,date,[NSString timestampFormatting:dateStr FormattingStyle:@"yyyy-MM-dd"]);
    self.timeStr = [NSString timestampFormatting:dateStr FormattingStyle:@"yyyy-MM-dd"];
    
}

#pragma mark - 国籍选择回调
-(void)didFinishCountry:(NSString*)country countryM:(JSCountryInfoModel *)m{
    if (![self.countryStr isEqualToString:country]) {
        self.cityStr = @"";
    }
    self.countryStr = country;
    
}
#pragma mark - 性别选择
-(void)didFinishGender:(NSString*)genderStr Gender:(UserGender)gender{
    self.gender = gender;
    self.genderStr = genderStr;
}

- (JSCountrySelectView *)countrySelectView{
    if (!_countrySelectView && userManager.countryDataSource.count) {
        _countrySelectView = [[JSCountrySelectView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 210) dataSource:userManager.countryDataSource];
        _countrySelectView.delegate = self;
    }
    return _countrySelectView;
}
@end
